//
//  OnlineEducationViewController.m
//  GC_OC
//
//  Created by 曾 on 2022/1/16.
//

#import "OnlineEducationViewController.h"
#import "OnlineEducationHeaderView.h"
#import "EducationTableViewCell.h"
#import "TearchFengCaiView.h"
#import "EducationTabCell.h"
#import "SdScrollView.h"
#import "TearchFengCaiView.h"
#import "YBPopupMenu.h"
#import "OnlineSubMenuVC.h"
#import "OnlineTopHeadView.h"
#import "CurriculumModel.h"
#import "NewHomeInfoCell.h"
#import "NewHomeInfoHeaderView.h"
#import "NewHomeInfoFooterView.h"
#import "FKBaseResult.h"

static NSString *const NewHomeInfoCellIdentifier = @"NewHomeInfoCell";

@interface OnlineEducationViewController ()<UITableViewDelegate,UITableViewDataSource,YBPopupMenuDelegate>

@property (nonatomic, strong)OnlineEducationHeaderView* headerView;
@property (nonatomic, strong)ObjectAFNetWorking* objectAFNet;
@property (nonatomic, strong)NSDictionary* dic;
@property (nonatomic, strong)UITableView* tableview;
@property (nonatomic,strong)TearchFengCaiView *teacherFCView;
@property (nonatomic,copy)NSString *currenClassID;//当前选择的班级ID
@property (nonatomic, strong)NSDictionary* currenClassDict;
@property (nonatomic,copy)NSString *classTitle;
@property (nonatomic,strong)OnlineTopHeadView *topSearchHeadView;
@property (nonatomic, strong) NSMutableSet *hideSectionSet;
@property (nonatomic, assign) BOOL notFirst;

@end

@implementation OnlineEducationViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    if ([SUPlayerManager manager].currentSong) {
        CGFloat height = 0;
        if (@available(iOS 13.0, *)) {
            NSSet *set = [UIApplication sharedApplication].connectedScenes;
            UIWindowScene *windowScene = [set anyObject];
            UIWindow *window = windowScene.windows.firstObject;
            height = window.safeAreaInsets.bottom;
        } else if (@available(iOS 11.0, *)) {
            UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
            height = window.safeAreaInsets.bottom;
        }
        height += 49;

        [[SUPlayerManager manager].bottomView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo([UIApplication sharedApplication].keyWindow);
            make.bottom.equalTo([UIApplication sharedApplication].keyWindow).offset(-height);
            make.height.mas_equalTo(60);
        }];
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (self.notFirst && !self.dic) {
        [self getData];
        self.notFirst = true;
    }
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatHeadView];
    self.objectAFNet=[[ObjectAFNetWorking alloc]init];
    self.hideSectionSet = [NSMutableSet set];
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    _tableview=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableview.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    _tableview.dataSource=self;
    _tableview.delegate=self;
    _tableview.showsVerticalScrollIndicator = NO;
    [_tableview registerClass:[EducationTabCell class] forCellReuseIdentifier:@"EducationTabCell"];
    
    UINib *lib = [UINib nibWithNibName:NewHomeInfoCellIdentifier bundle:nil];
    [_tableview registerNib:lib forCellReuseIdentifier:NewHomeInfoCellIdentifier];
    [_tableview registerClass:[NewHomeInfoHeaderView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([NewHomeInfoHeaderView class])];
    [_tableview registerClass:[NewHomeInfoFooterView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([NewHomeInfoFooterView class])];
    
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor = [UIColor colorWithRed:249/255.0 green:249/255.0 blue:249/255.0 alpha:1.0];
    self.tableview.backgroundColor = UIColor.whiteColor;
    self.tableview.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, 60)];
    [self.view addSubview:_tableview];
    if (@available(iOS 15.0, *)) {
        //[_tableview setValue:@20 forKey:@"sectionHeaderTopPadding"];
    }
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topSearchHeadView.mas_bottom).offset(0);
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(ISIphoneX?-34 - 44 :-44);
    }];
    
    [self getData];
}
//去除不同模块的轮播图
- (NSArray *)getSdCleScrollData:(NSString *)rotation{
    NSArray *rotationArray = self.currenClassDict[rotation];
    return rotationArray;
}
#pragma mark - TableViewDelete
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self getTableNums];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    } else {
        NSArray *classArray = [self getClassContentArray:section - 1];
        return classArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NewHomeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NewHomeInfoCellIdentifier];
    if (!cell) {
        cell = [[NewHomeInfoCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:NewHomeInfoCellIdentifier];
    }
    
    NSArray *classArray = [self getClassContentArray:indexPath.section - 1];
    NSDictionary *dict = classArray[indexPath.row];
    NSString *image = dict[@"image"];
    NSString *name = dict[@"name"];
    NSString *describe = dict[@"describe"];
    NSString *audio_num = dict[@"audio_num"];
    NSString *video_num = dict[@"video_num"];
    int video_numInt = video_num.intValue;
    int audio_numInt = audio_num.intValue;
    NSString * sNum = @"00:00";
    if (audio_numInt == 0 && video_numInt == 0) {
       sNum = @"00:00";
    }
    else if (audio_numInt != 0){
       sNum = [self timeFormatted:audio_numInt];
    }
    else if (video_numInt != 0){
       sNum = [self timeFormatted:video_numInt];
    }
    cell.titleLabel.text = [NSString isEmpty:name]?@"":name;

    cell.infoLabel.text = [NSString isEmpty:describe]?@"":describe;

    cell.timeLabel.text = [NSString isEmpty:sNum]?@"":sNum;

    NSString *img = [NSString isEmpty:image]?@"default":image;
    
    [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:img] placeholderImage:[UIImage imageNamed:@"default"]];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return  cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([self.hideSectionSet containsObject:[NSString stringWithFormat:@"%ld",indexPath.section]]) {
        return 0;
    }
    
    return  92;
//    return UITableViewAutomaticDimension;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    NewHomeInfoFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([NewHomeInfoFooterView class])];
    if (!footer) {
        footer = [[NewHomeInfoFooterView alloc]initWithReuseIdentifier:NSStringFromClass([NewHomeInfoFooterView class])];
    }
    return footer;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        CGFloat headVH = hig(53)+ hig(295);
        NSArray *teacher = self.currenClassDict[@"teacher"];
        if (teacher.count == 0) {
            headVH = 0;
        }
        UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,headVH)];
//        headView.backgroundColor = UIColor.blueColor;
        self.teacherFCView.dataSource = teacher;
        self.teacherFCView.mediClassID = self.idString;
        [headView addSubview:self.teacherFCView];
        self.teacherFCView.backgroundColor = UIColor.purpleColor;
        [self.teacherFCView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.left.mas_equalTo(wid(0));
            make.right.mas_equalTo(-wid(0));
            make.height.mas_equalTo(headVH);
        }];
        return headView;
    }
    else{
        
        NSString *headTitle = [self getTabHeadViewTitle:section - 1];
        
        NewHomeInfoHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([NewHomeInfoHeaderView class])];
        
        if (!header) {
            header = [[NewHomeInfoHeaderView alloc]initWithReuseIdentifier:NSStringFromClass([NewHomeInfoHeaderView class])];
        }
        header.titleLabel.text = headTitle;
        __weak typeof(self) weakSelf = self;
        header.hide = [self.hideSectionSet containsObject:[NSString stringWithFormat:@"%ld",section]];
        header.hideAction = ^(BOOL isHide) {
            [weakSelf hideInfoWithSection:section isHide:isHide];
        };
        return header;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        CGFloat headVH = hig(53)+ hig(295);
        NSArray *teacher = self.currenClassDict[@"teacher"];
        if (teacher.count == 0) {
            return 0;
        }
        return headVH;
    }
    else{
        return  62;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section != 0) {
        return 38;
    }
    return 0.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *classArray = [self getClassContentArray:indexPath.section - 1];
    NSDictionary *dict = classArray[indexPath.row];
    CurriculumModel *topModel = [[CurriculumModel alloc] initWithDic:dict];
    NSMutableArray *contentArray = [[NSMutableArray alloc]init];
    for (NSDictionary *dictt in classArray) {
        CurriculumModel *topModel = [[CurriculumModel alloc] initWithDic:dictt];
        [contentArray addObject:topModel];
    }
//    [[PlayModel sharedModel] play:topModel listArr:contentArray viewPlayY:SCREEN_HEIGHT - GCtabbarHeight - 50];
    NSLog(@"``c``lassArray~~>>%@",classArray);
    
//    [[GCAVPlayer shared] play:classArray andindex:indexPath.row ViewStatue:1 andIsAudio:YES];
    
    [SUPlayerManager manager].currentSongIndex = indexPath.row;
    [SUPlayerManager manager].songList = classArray.mutableCopy;
}
#pragma mark - lazy
- (BOOL)isValueTop{
    id top = self.currenClassDict[@"top"];
    if ([top isKindOfClass:[NSDictionary class]]) {
        return YES;
    }
    return NO;
}
- (BOOL)isValueBotom{
    id bottom = self.currenClassDict[@"bottom"];
    if ([bottom isKindOfClass:[NSArray class]]) {
        NSArray *bottomArray = (NSArray *)bottom;
        if (bottomArray.count != 0) {
            return YES;
        }
        return NO;
    }
    return NO;
}
//计算共要分为几组
- (NSInteger)getTableNums{
    NSInteger tatal = 1;
    id top = self.currenClassDict[@"top"];
    if ([top isKindOfClass:[NSDictionary class]]) {
        tatal++;
    }
    id bottom = self.currenClassDict[@"bottom"];
    if ([bottom isKindOfClass:[NSArray class]]) {
        NSArray *bottomArray = (NSArray *)bottom;
        tatal = bottomArray.count + tatal;
    }
    return tatal;
}
//获取标题
- (NSString *)getTabHeadViewTitle:(NSInteger)section{
    NSMutableArray *titleArray = [[NSMutableArray alloc]init];
    id top = self.currenClassDict[@"top"];
    if ([top isKindOfClass:[NSDictionary class]]) {
        NSDictionary *topDict = (NSDictionary *)top;
        NSString *nTitle = topDict[@"tile"];
        [titleArray addObject:nTitle];
    }
    id bottom = self.currenClassDict[@"bottom"];
    if ([bottom isKindOfClass:[NSArray class]]) {
        NSArray *bottomArray = (NSArray *)bottom;
        for (NSDictionary *botdict in bottomArray) {
            NSString *nTitle = botdict[@"tile"];
            [titleArray addObject:nTitle];
        }
    }
    return titleArray[section];
}
//组装所有的课程
- (NSArray *)getClassArrayData{
    NSMutableArray *DictArray = [[NSMutableArray alloc]init];
    id top = self.currenClassDict[@"top"];
    if ([top isKindOfClass:[NSDictionary class]]) {
        NSDictionary *topDict = (NSDictionary *)top;
        [DictArray addObject:topDict];
    }
    
    id bottom = self.currenClassDict[@"bottom"];
    if ([bottom isKindOfClass:[NSArray class]]) {
        NSArray *bottomArray = (NSArray *)bottom;
        for (NSDictionary *botdict in bottomArray) {
            [DictArray addObject:botdict];
        }
    }
    return DictArray;
}
//获取字典中content数组数据
- (NSArray *)getClassContentArray:(NSInteger)section{
    NSArray *classArray = [self getClassArrayData];
    NSDictionary *classDict = classArray[section];
    NSArray *content = classDict[@"content"];
    return content;
}
//取出bottom的第一个数据
- (NSString *)getClassBottomTitle{
    NSMutableArray *titleArray = [[NSMutableArray alloc]init];
    id bottom = self.currenClassDict[@"bottom"];
    if ([bottom isKindOfClass:[NSArray class]]) {
        NSArray *bottomArray = (NSArray *)bottom;
        for (NSDictionary *botdict in bottomArray) {
            NSString *nTitle = botdict[@"tile"];
            [titleArray addObject:nTitle];
        }
    }
    if (titleArray.count == 0) {
        return 0;
    }
    else{
        NSString *first = titleArray[0];
        return first;
    }
}
- (NSString *)timeFormatted:(int)totalSeconds{
    
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    return [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
}
-(void)creatHeadView{
    UIView* view=[[UIView alloc]initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,topHeight + 16)];
    view.backgroundColor=AppMainColor;
    
    [view addSubview:self.topSearchHeadView];
    [self.topSearchHeadView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(56);
    }];
    [self.view addSubview:view];
}

- (void)hideInfoWithSection:(NSInteger)section isHide:(BOOL)isHide{
    if (isHide) {
        [self.hideSectionSet addObject:[NSString stringWithFormat:@"%ld",section]];
    }else {
        [self.hideSectionSet removeObject:[NSString stringWithFormat:@"%ld",section]];
    }
    
    [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
}

//获取通过bottom32获取班级列表
-(void)getData{
    @weakify(self)
    [FKCacheTool getIndexData:self.idString complete:^(id data) {
        @strongify(self)
        self.dic = data;
        [self upDateView];
        [self updateTopHeadViewData];
    }];
}
//通过班级ID更新班级内容
- (void)makeUpdateClassData{
    NSDictionary *classInfo = [FKCacheTool classInfo];
    if (classInfo) {
        self.currenClassID = classInfo[@"id"];
        [self getClassContentData];
    } else {
        NSArray *media_class = self.dic[@"media_class"];
        if (media_class.count != 0) {
            NSDictionary *firstClass = media_class.firstObject;
            NSString *ID = firstClass[@"id"];
            self.currenClassID = ID;
            [self getClassContentData];
            [FKCacheTool saveClassInfo:firstClass];
        }
    }
}
//通过班级ID获取相关课程内容
-(void)getClassContentData{
    @weakify(self)
    [FKCacheTool getCateData:self.currenClassID complete:^(id data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            @strongify(self)
            //更新课程
            self.currenClassDict = data;
            //更新分类菜单内容
            self.headerView.dataSource = data[@"media_class"];
            self.headerView.sdScoImageArray = data[@"rotation_1"];
            [self.headerView reloadHeadView];
            [self.tableview reloadData];
        });
    }];
}
-(void)upDateView{
    [_headerView removeFromSuperview];
    _headerView=nil;
    self.tableview.tableHeaderView=self.headerView;
    [self makeUpdateClassData];
}
- (void)updateTopHeadViewData{
    self.topSearchHeadView.searchArray = self.dic[@"media_class"];
}
#pragma mark --lazy
- (OnlineTopHeadView *)topSearchHeadView{
    if (!_topSearchHeadView) {
        _topSearchHeadView = [[OnlineTopHeadView alloc]initWithFrame:CGRectZero];
        _topSearchHeadView.bgView.backgroundColor = AppMainColor;
        _topSearchHeadView.searchID = self.idString;
        WeakSelf(weakSlf)
        _topSearchHeadView.popMenuDidBlock = ^(NSString * _Nonnull ID) {
            [weakSlf makeUpdateClassData];
        };
    }
    return _topSearchHeadView;
}
-(OnlineEducationHeaderView*)headerView{
    if(!_headerView)
    {
        _headerView=[[OnlineEducationHeaderView alloc]initDic:self.dic];
        WeakSelf(weakSlf)
        _headerView.collDidBlock = ^(NSDictionary * _Nonnull dict) {
            NSLog(@"进入到子类");
            NSString *ID = dict[@"id"];
            NSString *name = dict[@"name"];
//            NSDictionary *mediaId = [[NSUserDefaults standardUserDefaults]objectForKey:@"SAVECLASSID"];
            NSString *lastName = weakSlf.topSearchHeadView.leftLabel.text;
            OnlineSubMenuVC *vc = [[OnlineSubMenuVC alloc]init];
            vc.hidesBottomBarWhenPushed=YES;
            vc.ID = ID;
            vc.mediCalssID = weakSlf.idString;
            if (![NSString isEmpty:lastName]) {
                vc.vcTitle = [NSString stringWithFormat:@"%@·%@",lastName,name];
            }
            else{
                vc.vcTitle = [NSString stringWithFormat:@"%@",name];
            }
            if ([ICMusicPlayManager sharedManager].narrowView) {
                [ICMusicPlayManager sharedManager].narrowView.frame = CGRectMake(0, SCREEN_HEIGHT - 50 - HY_BottomWhiteBar_Height, SCREEN_WIDTH, 50);
            }
            [weakSlf.navigationController pushViewController:vc animated:NO];
        };
    }
    return _headerView;
}
- (TearchFengCaiView *)teacherFCView {
    if (!_teacherFCView) {
        _teacherFCView = [[TearchFengCaiView alloc]initWithFrame:CGRectZero];
    }
    return _teacherFCView;
}
@end
